/**
 * Created by Acer on 2017/11/1.
 */
(function (angular) {
	//1.创建模块
	var app = angular.module('service', []);

	//2.创建服务
	app.service('myService', ['$window', function($window){

		//1.获取数据
		this.getData = function(){
			return JSON.parse($window.localStorage.getItem('tasks')|| '[]');
		}
		//2.保存数据
		this.setData = function(data){
			console.log(22222);
			$window.localStorage.setItem('tasks', JSON.stringify(data));
		}

		//3.添加任务
		this.add = function(data, newTodo){
			data.push({
				id :Math.random(),
				content: newTodo,
				completed:false
			})
			this.setData(data);
		}

		//4.删除任务
		this.delete = function(data, id){
			for(var i = 0; i < data.length; i++){
				if(data[i].id === id){
					data.splice(i, 1);
					this.setData(data);
				}
			}
		}

		//5.批量切换任务状态
		this.toggleAll = function(data, selectAll){
			for(var i = 0; i < data.length; i++){
				data[i].completed = selectAll;
			}
			this.setData(data);
		}

		// 6获取未完成任务数据
		this.getActive = function(data){
			var count = 0
			// 遍历todos, 找到所有completed属性值为false的数据
			for (var i = 0; i < data.length; i++) {
				var item = data[i]
				if(!item.completed){
					count++
				}
			}
			return count
		}

		//7.清除所有任务
		this.removeAll = function(data){
			for(var i = data.length - 1; i >= 0; i--){
				if(data[i].completed){
					data.splice(i, 1);
				}
			}
			this.setData(data);
		}
	}]);
})(angular);
